#include "stdafx.h"
#include "ZFrameAllocator.h"
#include <assert.h>

namespace	Z	{

//------------------------------------------------------------------------------------------------------------------------
FrameAllocator::FrameAllocator(size_t stackkSize)
:	mStackSize(stackkSize),
	mMarker(0),
	mStack(new byte_t[stackkSize])
{
}

FrameAllocator::~FrameAllocator()	{
}
	
void* FrameAllocator::allocateUnaligned(size_t kSize)
{
	assert(mMarker + kSize <= mStackSize);
	void* memory	= mStack.get() + mMarker;
	mMarker	+= kSize;
	return memory;
}

void* FrameAllocator::allocateAligned(size_t kSize, size_t alignment)
{
	if(alignment == 1)
		return allocateUnaligned(kSize);
	const size_t expanedSize	= kSize + alignment;
	const byte_t* rawAddress	= (byte_t*)allocateUnaligned(expanedSize);
	const size_t mask	= (alignment - 1);
	const size_t misalignment	= ((size_t)rawAddress & mask);
	const size_t adjustment	= alignment - misalignment;
	const byte_t* alignedAddress	= rawAddress + adjustment;
//	const byte_t* pAdjustment	= (byte_t*)(alignedAddress - 1);
//	*pAdjustment	= adjustment;
	return (void*)alignedAddress;
}

}